<template>
  <div class="user">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">主页</el-breadcrumb-item>
      <el-breadcrumb-item>安全管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="my-query">
      <el-form size="mini" :inline="true" :model="query">
        <el-form-item label="状态">
          <el-select v-model="query.u_status" @change="getPage(1)">
            <el-option label="全部" value></el-option>
            <el-option
              v-for="item in userStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="账号">
          <el-input v-model="query.u_id"></el-input>
        </el-form-item>

        <el-form-item label="姓名">
          <el-input v-model="query.u_name"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click.prevent="getPage(1)">查询</el-button>
          <el-button
            v-if="query.u_status==='00'"
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click.prevent="openAdd"
          >新增</el-button>
          <el-button
            v-if="query.u_status==='00'"
            type="primary"
            icon="el-icon-delete"
            @click.prevent="execDel"
          >删除</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="my-data">
      <el-table
        :data="page.rows"
        style="width: 100%"
        :fit="true"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="u_id" label="账号"></el-table-column>
        <el-table-column prop="u_name" label="姓名"></el-table-column>
        <el-table-column prop="status_name" label="状态"></el-table-column>

        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button v-if="scope.row.u_status==='00'" @click="openUpd(scope.row)" type="text" size="mini" >修改</el-button>
            <el-button v-if="scope.row.u_status==='00'" @click="execSingleDel(scope.row.u_id)" type="text" size="mini" >删除</el-button>
            
            <el-button v-if="scope.row.u_status==='00'" @click="execStatusChange(scope.row.u_id,'confirm')" type="text" size="mini" >确定</el-button>
            <el-button v-if="scope.row.u_status==='55'" @click="execStatusChange(scope.row.u_id,'unuse')" type="text" size="mini" >禁用</el-button>
            <el-button v-if="scope.row.u_status==='77'" @click="execStatusChange(scope.row.u_id,'reuse')" type="text" size="mini" >启用</el-button>

            <el-button v-if="scope.row.u_status==='55'" @click="assignRoles(scope.row)" type="text" size="mini" >角色</el-button>  
          
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="my-opr">
      <!-- .sync用于vue组件的属性，其效果是和数据产生双向绑定 -->
      <el-pagination
        :page-sizes="sizeList"
        :page-size.sync="query.pageSize"
        :current-page.sync="query.pageNum"
        layout="sizes,prev, pager, next,jumper,->,total"
        :total="page.total"
        @current-change="getPage(query.pageNum)"
        @size-change="getPage(1)"
      ></el-pagination>
    </div>

    <!-- 新增对话框 -->
    <el-dialog title="新增用户" :visible.sync="dialogAddVisible" width="40%">
      <el-form :model="addObj" :rules="addRules" ref="addForm">
        <el-form-item label="账号" prop="u_id" :label-width="dialogLabelWidth">
          <el-input v-model="addObj.u_id" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="u_name" :label-width="dialogLabelWidth">
          <el-input v-model="addObj.u_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddVisible = false">取 消</el-button>
        <el-button type="primary" @click.prevent="execAdd">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog title="修改用户" :visible.sync="dialogUpdVisible" width="40%">
      <el-form :model="updObj" :rules="updRules" ref="updForm">
        <el-form-item label="账号" prop="u_id" :label-width="dialogLabelWidth">
          <el-input v-model="updObj.u_id" autocomplete="off" :readonly="true" ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="u_name" :label-width="dialogLabelWidth">
          <el-input v-model="updObj.u_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUpdVisible = false">取 消</el-button>
        <el-button type="primary" @click.prevent="execUpd">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 角色窗口 -->
    <el-dialog :title="`${selectedUser.u_name}的角色`" :visible.sync="dialogRoleVisible" width="60%">

      <el-checkbox-group v-model="userRoleIdList" >
        <div  class="my-roles">
          <el-checkbox v-for="role in roleList" :key="role.ro_id" :label="role.ro_id" :border="true" style="width:150px;padding:10px;margin:10px;" >{{role.ro_name}}</el-checkbox>
        </div>    
      </el-checkbox-group>


      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click.prevent="confirmRoles">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    var validateUserId = (rule, value, callback) => {
      this.$axios.get(`safty/user/${value}`).then(response => {
        let result = response.data;
        if (result.success) {
          callback();
        } else {
          callback(new Error(result.message));
        }
      });
    };

    return {
      currSelectedRows: [], //当前选择的数据
      query: {
        pageNum: 1,
        pageSize: 5,
        //查询条件
        u_status: "",
        u_id: "",
        u_name: ""
      },

      page: {}, //分页对象封装了分页数据

      sizeList: [2, 3, 5, 10, 15, 20, 30],

      //状态列表
      userStatus: [
        { value: "00", label: "未确定" },
        { value: "55", label: "已启用" },
        { value: "77", label: "已禁用" }
      ],

      //用户数据列表
      list: [],

      dialogLabelWidth: "50px", //窗口表单域提示label的宽度

      dialogAddVisible: false, //新增对话框是否显示
      addObj: {}, //新增数据

      dialogUpdVisible: false, //修改对话框是否显示
      updObj: {}, //修改数据


      //验证规则
      addRules: {
        u_id: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" },
          { validator: validateUserId, trigger: "blur" }
        ],
        u_name: [{ required: true, message: "请输入姓名", trigger: "blur" }]
      },

      updRules: {
        u_id: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" }
        ],
        u_name: [{ required: true, message: "请输入姓名", trigger: "blur" }]
      },

      //当前分配角色的用户
      selectedUser:{},
      dialogRoleVisible:false,
      roleList:[],
      userRoleIdList:[],//用户拥有角色的id集合



    };
  },
  methods: {
    //多选框发生选项改变时的响应函数，该函数的参数就是当前选择的选项
    handleSelectionChange(val) {
      //console.log(val);
      this.currSelectedRows = val;
    },

    //获取列表
    getPage(pageNum) {
      this.query.pageNum = pageNum;
      this.$axios.get("safty/user", { params: this.query }).then(response => {
        //this.list = response.data;
        this.page = response.data;

        //用服务器端返回的数据（页码和每页记录数修正查询参数中的页码和每页记录数）
        this.query.pageNum = this.page.curr;
        this.query.pageSize = this.page.pageSize;
      });
    },
    //打开新增窗口
    openAdd() {
      this.dialogAddVisible = true; //显示对话框
    },

    //打开修改窗口
    openUpd(obj) {
      this.updObj ={...obj};//将obj的属性拷贝给updObj
      this.dialogUpdVisible = true; //显示对话框
    },

    //执行新增
    execAdd() {
      this.$refs["addForm"].validate(valid => {
        if (valid) {
          this.$axios.post("safty/user", this.addObj).then(response => {
            let result = response.data;
            if (result.success) {
              this.getPage(1); //刷新数据
              this.dialogAddVisible = false; //关闭窗口
              this.$refs["addForm"].resetFields(); //重置表单
              this.$message.success({
                message: result.message
              });
            } else {
              this.$message.error(result.message);
            }
          });
        } else {
          return false; //验证没有通过必须return false;
        }
      });
    },

    //执行修改
    execUpd() {
      this.$refs["updForm"].validate(valid => {
        if (valid) {
          this.$axios.put("safty/user", this.updObj).then(response => {
            let result = response.data;
            if (result.success) {
              this.getPage(1); //刷新数据
              this.dialogUpdVisible = false; //关闭窗口
              this.$refs["updForm"].resetFields(); //重置表单
              this.$message.success({
                message: result.message
              });
            } else {
              this.$message.error(result.message);
            }
          });
        } else {
          return false; //验证没有通过必须return false;
        }
      });
    },

    //执行删除
    execDel() {
      if (!this.currSelectedRows || this.currSelectedRows.length == 0) {
        this.$message.warning({
          message: "您没有选择数据记录！",
          duration: 1200
        });
        return;
      }

      let ids = [];
      for (let obj of this.currSelectedRows) {
        ids.push(obj.u_id);
      }

      this.$axios.delete("safty/user", { data: ids }).then(response => {
        let result = response.data;
        if (result.success) {
          this.getPage(this.page.curr); //刷新数据
          this.$message.success({
            message: result.message
          });
        } else {
          this.$message.error(result.message);
        }
      });
    },

    //执行单条记录的删除
    execSingleDel(id) {
      //console.log(id);
      this.$confirm("您确实要删除该条用户信息吗?", "提示", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {

            const loading = this.$loading({
              lock: true,
              background: "rgba(0, 0, 0, 0.7)"
            });

            this.$axios.delete(`safty/user/${id}`)
            .then(response => {
              loading.close();
              let result = response.data;
              if (result.success) {
                this.getPage(this.page.curr); //刷新数据
                this.$message.success({
                  message: result.message
                });
              } else {
                this.$message.error(result.message);
              }
            })
            .catch(()=>{
              loading.close();
            });

        })
        .catch(() => {
         
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    execStatusChange(id,opr){
      let oprName;
      switch(opr){
        case 'confirm':oprName = '确定';break;
        case 'unuse':oprName = '禁用';break;
        case 'reuse':oprName = '启用';break;
        default: oprName = '';        
      }
      this.$myPut(`safty/user/${id}/${opr}`,null,{title:'提示',message:`您确实要执行${oprName}操作吗？`})
          .then(()=>{//then方法中的函数是成功后需要执行的逻辑
            this.getPage(this.page.curr);
          });

    },

    //获得所有的角色
    getRoleList(){
      this.$myGet('safty/user/role')
          .then(roleList=>{
            this.roleList=roleList;
          });
    },

    //分配角色（打开角色窗口）
    assignRoles(user){
      this.selectedUser=user;

      this.$myGet('safty/user/roleIds/'+user.u_id)//获取当前用户拥有的角色Ids
          .then(roleIds=>{
            this.userRoleIdList=roleIds;
            this.dialogRoleVisible=true;
          });

      
    },

    //确认角色
    confirmRoles(){
      this.$myPut('safty/user/role',{u_id:this.selectedUser.u_id,roleIds:this.userRoleIdList});
    }



  },
  mounted() {
    this.getPage(1);
    this.getRoleList();
  }
};
</script>

<style scoped>
.user {
  /*background-color: aqua;*/
  height: 100%;
  width: 100%;
  position: relative;
}
.my-query {
  position: absolute;
  left: 0px;
  top: 30px;

  width: 100%;
  height: 46px;
  text-align: left;
}
.my-data {
  position: absolute;
  left: 0px;
  top: 80px;
  bottom: 35px;

  width: 100%;
}

.my-opr {
  position: absolute;
  left: 0px;
  bottom: 0px;

  width: 100%;
  text-align: left;
}

.my-roles{
  display:flex;
  flex-direction: row;
  justify-content:flex-start;
  flex-wrap: wrap;

  border:1px solid red;
}
</style>